package com.mdsoft.group.core;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;


public class GroupDispatch {

	private int groupCount = 0;
	private int peopleCount = 0;
	
	public List<Group> dispatch(List<People> peoples, List<Choose> chooses, int groupCount) {
		Context context = Context.getInstance();
		context.setAllChoose(new AllChoose(chooses));
		context.setAllPeople(peoples);
		this.peopleCount = peoples.size();
		this.groupCount = groupCount;
		initGroup();
		for (int i = 0; i < 500; i++) {
			
			System.out.println(Context.getInstance().getAllGroup());
			System.out.println(Context.getInstance().getTotalContentment());
			List<People> outPeoples = new ArrayList<People>();
			for (Group group : Context.getInstance().getAllGroup()) {
				outPeoples.add(group.goOutPeople());
			}
			addOutPeoples(outPeoples, Context.getInstance().getAllGroup());
		}
		return Context.getInstance().getAllGroup();
	}

	private void addOutPeoples(List<People> peoples, List<Group> groups) {
		List<People> copyPeoples = new ArrayList<People>(peoples);
		List<Group> copyGroups = new ArrayList<Group>(groups);
		
		People goodPeople = null;
		Group goodGroup = null;
		while (copyPeoples.size() > 0) {
			goodGroup = copyGroups.get(0);
			goodPeople = copyPeoples.get(0);
			float maxRelation = Float.MIN_VALUE;
			for (People people : copyPeoples) {
				for (Group group : copyGroups) {
					float relation = group.checkContentment(people);
					if (maxRelation < relation) {
						maxRelation = relation;
						goodGroup = group;
						goodPeople = people;
					}
				}
			}
			
			goodGroup.add(goodPeople);
			copyGroups.remove(goodGroup);
			copyPeoples.remove(goodPeople);
		}
		
	}

	private void initGroup() {
		Context context = Context.getInstance();
		randomList(context.getAllPeople());
		List<Group> allGroups = new ArrayList<Group>();
		for (int i = 0; i < groupCount; i++) {
			List<People> peoples = context.getAllPeople().subList(i * peopleCount / groupCount, (i + 1) * peopleCount / groupCount);
			Group group = new Group(peoples);
			allGroups.add(group);
		}
		context.setAllGroup(allGroups);
	}
	
	private void randomList(List<People> list) {
		Random random = new Random();
		int size = list.size();
		for (int i = 0; i < size; i++) {
			int tmpRnd = random.nextInt(size);
			People object = list.get(tmpRnd);
			list.set(tmpRnd, list.get(i));
			list.set(i, object);
			
		}
	}
}
